//
//  DiscoveryViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/4.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "DiscoveryViewController.h"
#import "RecentlyChatListViewController.h"
#import "NearbyFriendCell.h"
#import "DiscoveryHeaderView.h"
#import "PersonalInfomationViewController.h"
#import "ChatViewController.h"


@interface DiscoveryViewController ()<UITableViewDelegate,UITableViewDataSource>
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 haderview
 */
@property (nonatomic , strong) DiscoveryHeaderView *headerView;
/**
 currentPage
 */
@property (nonatomic , assign) int currentPage;
/**
 longitude
 */
@property (nonatomic , assign) double longitude;
/**
 latitude
 */
@property (nonatomic , assign) double latitude;
@end

@implementation DiscoveryViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}


#pragma mark - init method

- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
   // [self.view addSubview:self.headerView];
    [self.view addSubview:self.myTableView];
}


- (void) initLayout {
    
   // self.myTableView.frame = CGRectMake(0, - TJ_StatusBarHeight_Define, KScreenWidth, KScreenHeight - TJ_TabBarHeight);
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];

}


- (void) initAction {
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArr removeAllObjects];
        self.currentPage = 1;
        [self bannerRequest];
        [self dataRequest];
    }];
    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.currentPage ++;
        [self dataRequest];
    }];
    self.myTableView.mj_footer.hidden = YES;
    
    [self.headerView.allBtn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.manBtn addTarget:self action:@selector(manBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.womanBtn addTarget:self action:@selector(womanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    @weakify(self);
    //我想聊聊
    [self.headerView.chatBtn setTapped:^{
        @strongify(self);
        [self chat];
    }];
}


- (void)initData {
    self.currentPage = 1;
    
    //广告轮播请求
    [self bannerRequest];

    //定位
    @weakify(self);
    [[LocationManager sharedManager] startLocationCompleteBlock:^(double latitude, double longitude) {
        @strongify(self);
        self.longitude = longitude;
        self.latitude = latitude;

        [self dataRequest];
    }];
}


#pragma mark - delegate


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NearbyFriendCell *cell = [NearbyFriendCell cellWithTableView:tableView];
    if (self.dataArr.count > indexPath.row) {
        NearbyFriends *model = self.dataArr[indexPath.section];
        
        cell.model = model;
        //聊一聊  or  加好友
        @weakify(self);
        [cell setAddOrChatBlock:^(AddFriendOrChatType addFriendOrChatType) {
            @strongify(self);
            if (addFriendOrChatType == AddFriendOrChatTypeAdd) {
                
                //添加好友
                AddFriendVerifyViewController *vc = [[AddFriendVerifyViewController alloc] init];
                vc.identifier = model.memberNum;
                [self.navigationController pushViewController:vc animated:YES];
            } else if (addFriendOrChatType == AddFriendOrChatTypeChat) {
                //开始聊天
                [self beginChatWithIdentifier:model.name];
            }
        }];
        //去店铺
        [cell setGotoShopBlock:^{
            
        }];
        return cell;
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NearbyFriends *model = self.dataArr[indexPath.section];
    
    PersonalInfomationViewController *vc = [[PersonalInfomationViewController alloc] init];
    vc.friendId = model.memberId;
    vc.memberNum = model.memberNum;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - target action
- (void)allBtnClick:(UIButton *)button {
    self.headerView.allBtn.selected = YES;
    self.headerView.manBtn.selected = NO;
    self.headerView.womanBtn.selected = NO;
    self.currentPage = 1;
    [self.dataArr removeAllObjects];
    [self dataRequest];
}
- (void)manBtnClick:(UIButton *)button {
    self.headerView.manBtn.selected = YES;
    self.headerView.allBtn.selected = NO;
    self.headerView.womanBtn.selected = NO;
    self.currentPage = 1;
    [self.dataArr removeAllObjects];
    [self dataRequest];
}
- (void)womanBtnClick:(UIButton *)button {
    self.headerView.womanBtn.selected = YES;
    self.headerView.allBtn.selected = NO;
    self.headerView.manBtn.selected = NO;
    self.currentPage = 1;
    [self.dataArr removeAllObjects];
    [self dataRequest];
}


#pragma mark - private method
- (void)dataRequest {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    //未登录状态
    if ([JTool iSNull:memberId]) {
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
        return;
    }
    NearbyFriendsParam *param = [[NearbyFriendsParam alloc] init];
    param.page = self.currentPage;
    param.limit = 10;
    double longitude = self.longitude ? self.longitude : 0;
    double latitude = self.longitude ? self.latitude : 0;
    
    param.longitude = [NSString stringWithFormat:@"%f",longitude];
    param.latitude = [NSString stringWithFormat:@"%f",latitude];
    param.memberId = memberId;
    NSNumber *sexType = @0;
    if (self.headerView.allBtn.selected) {
        sexType = @0;
    } else if (self.headerView.manBtn.selected) {
        sexType = @1;
    } else if (self.headerView.womanBtn.selected) {
        sexType = @2;
    }
    param.sex = sexType;//0是全部  1男 2女
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] nearbyFriendsWithParam:param] subscribeNext:^(NearbyFriendsList * _Nullable nearbyFriendsList) {
        
        [self.dataArr addObjectsFromArray:nearbyFriendsList.list];
        [self.myTableView reloadData];
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
        if (self.currentPage == [nearbyFriendsList.totalPage intValue] || [nearbyFriendsList.totalPage intValue] == 0) {
            [self.myTableView.mj_footer endRefreshingWithNoMoreData];;
        } else {
            self.myTableView.mj_footer.hidden = NO;
        }
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
    }];
}


//广告轮播
- (void)bannerRequest {
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getDiscoveryAdvertising] subscribeNext:^(MessageList * _Nullable messageList) {
        @strongify(self);
        NSMutableArray *tempArr = [[NSMutableArray alloc] init];
        for (Message *model in messageList.list) {
            [tempArr addObject:model.imgName];
        }
        self.headerView.cycleView.imageURLStringsGroup = tempArr;
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
    }];
}


//我想聊聊
- (void)chat {
    
    //校验聊天是否登陆成功，否则重新登录
    if ([UserInfoDataProvider sharedInstance].userInfo.isIMLogin) {
        
        @weakify(self);
        [self pushToViewController:^{
            @strongify(self);
            [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
        }];
        
    } else {
        //如果没登录过
        NSString *userSig = [UserInfoDataProvider sharedInstance].userInfo.userSig;
        NSString *userName = [UserInfoDataProvider sharedInstance].userInfo.memberNum;
        [[ChatManager sharedInstance] loginIMWithUserName:userName userSig:userSig succ:^{
            [self toastWithContent:@"聊天登录成功"];
            UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
            userInfo.isIMLogin = YES;
            [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        } fail:^(int code, NSString * _Nonnull msg) {
            [self toastWithContent:msg];
        }];
        [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
    }
}


//聊天
- (void)beginChatWithIdentifier:(NSString *)identifier {
    TUIConversationCellData *data = [[TUIConversationCellData alloc] init];
    data.convId = identifier;
    data.convType = TIM_C2C;
    data.title = identifier;
    ChatViewController *chat = [[ChatViewController alloc] init];
    chat.conversation = data;
    [self.navigationController pushViewController:chat animated:YES];
}


#pragma mark - getter and setter
- (UITableView *)myTableView {
    
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.tableHeaderView = self.headerView;
        _myTableView.estimatedRowHeight = 297;
        _myTableView.rowHeight = UITableViewAutomaticDimension;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        UIView *footer = [[UIView alloc] init];
        footer.backgroundColor = mBackgroudColor;
        footer.frame = CGRectMake(0, 0, KScreenWidth, 10);
        _myTableView.tableFooterView = footer;
    }
    return _myTableView;
}


- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (DiscoveryHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[DiscoveryHeaderView alloc] initWithFrame:CGRectMake(0, TopBarHeight, SCREEN_WIDTH, ScaleHeight(200) + 332)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}
@end

